<template>
  <div class="common-table">
    <div class="table-item">
      <formItem title="名称" sub="*">
        <template v-slot:right>
          <el-input
              v-model="formObj.name"
              placeholder="请输入名称"
              type="text"
          />
        </template>
      </formItem>
      <formItem title="位置" sub="*">
        <template v-slot:right>
          <el-input
              v-model="formObj.location"
              placeholder="请输入位置"
              type="text"
          />
        </template>
      </formItem>
      <formItem title="面积" sub="*">
        <template v-slot:right>
          <el-input
              v-model="formObj.area"
              placeholder="请输入面积(亩)"
              type="text"
          />
        </template>
      </formItem>
    </div>
    <div class="table-item">
      <formItem title="区镇" sub="*">
        <template v-slot:right>
          <el-select
              v-model="formObj.town"
              popper-class="big-screnn-popper"
              placeholder="请选择区镇"
          >
            <el-option
                v-for="item in cityOption"
                :key="item.value"
                :label="item.value"
                :value="item.value"
            />
          </el-select>
        </template>
      </formItem>
      <formItem title="类型" sub="*">
        <template v-slot:right>
          <el-select
              v-model="formObj.type"
              popper-class="big-screnn-popper"
              placeholder="请选择类型"
          >
            <el-option
                v-for="item in typeOption"
                :key="item.value"
                :label="item.value"
                :value="item.value"
            />
          </el-select>
        </template>
      </formItem>
      <formItem title="供地方式" sub="*">
        <template v-slot:right>
          <el-select
              v-model="formObj.methods"
              popper-class="big-screnn-popper"
              placeholder="请选择供地方式"
          >
            <el-option
                v-for="item in landTypeOption"
                :key="item.value"
                :label="item.value"
                :value="item.value"
            />
          </el-select>
        </template>
      </formItem>
    </div>
    <div class="table-item">
      <formItem title="用途" sub="*">
        <template v-slot:right>
          <el-select
              v-model="value1"
              popper-class="big-screnn-popper"
              placeholder="请选择用途"
              allow-create
              clearable
              filterable
              multiple
              collapse-tags
              collapse-tags-tooltip
          >
            <el-option
                v-for="item in useOption"
                :key="item.value"
                :label="item.value"
                :value="item.value"
            />
          </el-select>
        </template>
      </formItem>
      <formItem title="申报时间" sub="*">
        <template v-slot:right>
          <el-date-picker
              v-model="formObj.reportTime"
              type="date"
              placeholder="选择日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
          />
        </template>
      </formItem>
      <formItem title="计划上市时间" sub="*">
        <template v-slot:right>
          <el-date-picker
              v-model="formObj.planTime"
              type="date"
              placeholder="选择日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
          />
        </template>
      </formItem>
      <!-- 为了保证space-between样式能完整生效，空的formitem需要加一个div放这里即可 -->
      <div class="empty-form-item"></div>
    </div>
    <div class="table-item">
      <formItem title="计划土壤污染调查启动时间" sub="*">
        <template v-slot:right>
          <el-date-picker
              v-model="formObj.testTime"
              type="date"
              placeholder="选择日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
          />
        </template>
      </formItem>
    </div>
    <div class="table-item">
      <div class="table-full-text">
        <div class="left" v-if="formObj.fileName === ''">
          <span>数据导入</span>
        </div>

        <div class="right">
          <div class="red-line">
            <formItem title="数据导入" v-if="formObj.fileName !== ''">
              <template v-slot:right>
                <el-input v-model="formObj.fileName" placeholder="请输入名称" type="text"/>
              </template>
            </formItem>
            <el-upload
                action="api/analyseKMZ"
                :on-success="handleAvatarSuccess"
                method="post"
                :show-file-list="false"
            >
              <el-button type="primary">点击上传</el-button>
            </el-upload>
            <div style="margin-left: 10px">
              <el-button type="primary" @click="clear">取消上传</el-button>
              <el-button type="primary" @click="batchUpload">批量上传</el-button>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="tips-text">
      <span>1.只能上传.kmz文件，且不超过512MB</span>
    </div>
    <div class="tips-text1">
      <span>2.点击取消上传后,可重新上传地块数据</span>
    </div>
    <div class="tips-text1">
      <span>3.带*为必填项</span>
    </div>
    <div class="fix-operate-map">
      <el-dialog v-model="dialogTimeVisible" custom-class="detail-progress-modal detail-timeline-modal"
                 :draggable="true">
        <template v-slot:title>
          <div class="header-modal-two">
            <div class="modal-content-header-title">
              <span>批量上传</span>
            </div>
          </div>
        </template>
        <el-upload
            class="upload-demo"
            ref="uploadFile"
            drag
            :http-request="createLand"
            multiple
            :limit="5"
        >
          <el-icon class="el-icon--upload">
            <Upload/>
          </el-icon>
          <div class="el-upload__text">
            <span>将批量文件拖拽到这边创建地块</span>
          </div>
        </el-upload>
        <el-button type="primary" @click="upload">确认上传</el-button>
      </el-dialog>
    </div>
  </div>
</template>
<script lang="ts">
import {
  reactive,
  defineComponent,
  watch,
  getCurrentInstance,
  onMounted, ref,
} from "vue";
import formItem from "@/components/commonFomItem/index.vue";
import {ElNotification, UploadProps} from "element-plus";
import * as turf from "@turf/turf";
import {syncBuiltinESMExports} from "module";
import {Upload} from '@element-plus/icons-vue'
import type {UploadInstance} from 'element-plus';
import Data from "../../../public/config/data.json"

export default defineComponent({
  components: {formItem, Upload},
  props: ["state", "isInsert"],
  emits: ["data"],
  setup(props, context) {
    const userType = localStorage.getItem("userType");
    const loginName = localStorage.getItem("loginName");
    //获取当前时间
    const getCurrentTime = () => {
      let date = new Date();
      //年
      let year = date.getFullYear().toString();
      //月份是从0月开始获取的，所以要+1;
      let month = ''
      if ((date.getMonth() + 1) < 10) {
        month = '0' + (date.getMonth() + 1).toString()
      } else {
        month = (date.getMonth() + 1).toString()
      }
      //日
      let day = date.getDate().toString();
      //时
      let hour = date.getHours().toString();

      return year + '年' + month + '月' + day + '日' + hour + '时'
    }
    const uploadFile = ref<UploadInstance>();
    const instance = getCurrentInstance();
    const yjs = instance?.appContext.config.globalProperties.yjs;
    const Cesium = instance?.appContext.config.globalProperties.Cesium;
    const {appContext} = getCurrentInstance();
    const cityOption = reactive(Data).selectTown
    //用途
    const useOption = reactive(Data).useOption
    //供地方式
    const landTypeOption = reactive(Data).landClass
    //类型
    const typeOption = reactive(Data).type
    const value1 = ref([])
    const formObj = reactive({
      id: "",
      name: "",
      location: "",
      area: "",
      town: "",
      type: "",
      methods: "",
      geom: "",
      use: "",
      reportTime: "",
      planTime: "",
      testTime: "",
      fileName: ''
    });
    const dialogTimeVisible = ref(false)
    const isUpload = ref(false)
    //创建用途字段
    const createUse = () => {
      for (let i = 0; i < value1.value.length; i++) {
        if (formObj.use === '') {
          formObj.use = value1.value[i] + formObj.use
        } else {
          formObj.use = formObj.use + ',' + value1.value[i]
        }
      }
    }
    //打开批量上传
    const batchUpload = () => {
      appContext.config.globalProperties
          .axios({
            url: `api/batchInsert/start`,
            method: "post",
            data: formObj,
          }).then(() => {
        uploadFile.value!.clearFiles()
        isUpload.value = false
      })
      dialogTimeVisible.value = true
    }

    //执行批量上传
    const createLand = (option) => {
      appContext.config.globalProperties
          .axios({
            url: `api/batchInsert/getValue`,
            method: "post",
            data: formObj,
            transformRequest: [function () {
              let oMyForm = new FormData();
              oMyForm.append("file", option.file);
              return oMyForm;
            }],
          }).then(() => {
        isUpload.value = true
      })
    }
    //批量上传结束
    const upload = () => {
      if (isUpload.value === true) {
        appContext.config.globalProperties
            .axios({
              url: `api/batchInsert/confirm`,
              method: "post",
              data: formObj,
              transformRequest: [function (data) {
                let oMyForm = new FormData();
                oMyForm.append("userType", userType);
                oMyForm.append("content", loginName + "于" + getCurrentTime() + "，创建了");
                oMyForm.append("infoDate", getCurrentTime());
                return oMyForm;
              }]
            })
            .then(() => {
              isUpload.value = false
              uploadFile.value!.clearFiles()
              ElNotification({
                title: "传送地块数据",
                message: "上传成功",
                type: "success",
                position: "top-left",
                offset: 300,
              });
            });
      } else {
        ElNotification({
          title: "传送地块数据",
          message: "未上传地块数据",
          type: "success",
          position: "top-left",
          offset: 300,
        });
      }

    }

    //获取id值
    onMounted(() => {
      appContext.config.globalProperties
          .axios({
            url: `api/search/id`,
            method: "post",
            data: formObj,
          })
          .then((response) => {
            formObj.id = response.data;
          });
    });

    //取消数据
    const clear = () => {
      formObj.fileName = ""
      formObj.geom = "";
      ElNotification({
        title: "取消上传数据",
        message: "取消成功",
        type: "success",
        position: "top-left",
        offset: 300,
      });
    };

    //点击确认按钮进行操作
    watch(
        () => props.state, () => {
          createUse()
          context.emit("data", formObj);
        }
    )

    //数据插入成功后进行操作
    watch(
        () => props.isInsert,
        (cur) => {
          let points = [];
          let str = formObj.geom;
          points = str.split(" ");
          let turfcoords = [];
          let degArray = [];
          for (let i = 1; i < points.length; i++) {
            let point = points[i].split(",");
            let turfpoint = [];
            turfpoint.push(point[0] * 1);
            turfpoint.push(point[1] * 1);
            degArray.push(point[0] * 1);
            degArray.push(point[1] * 1);
            turfcoords.push(turfpoint);
          }
          let _color = Cesium.Color.fromCssColorString("#D13939");
          var _entity = new Cesium.Entity({
            name: "land." + formObj.id,
            polyline: {
              positions: Cesium.Cartesian3.fromDegreesArray(degArray),
              width: 2.5,
              // arcType: Cesium.ArcType.NONE,
              material: _color,
              classificationType: Cesium.ClassificationType.BOTH,
            },
            polygon: {
              hierarchy: {
                positions: Cesium.Cartesian3.fromDegreesArray(degArray),
              },
              material: Cesium.Color.fromAlpha(_color, 0.5),
              classificationType: Cesium.ClassificationType.TERRAIN,
              outline: true, // height is required for outline to display
            },
          });

          var polygon = turf.polygon([turfcoords]);

          // var polygon = turf.polygon([turfcoords]);

          var center = turf.centerOfMass(polygon);

          var _pointEntity = new Cesium.Entity({
            name: "land." + formObj.id,
            position: Cesium.Cartesian3.fromDegrees(
                center.geometry.coordinates[0],
                center.geometry.coordinates[1],
                20
            ),
            billboard: {
              image: "img/step1.png",
              scale: 1,
              scaleByDistance: new Cesium.NearFarScalar(1000, 1.0, 40000, 0.5),
              distanceDisplayCondition: new Cesium.DistanceDisplayCondition(
                  0.0,
                  60000
              ),
            },

            label: {
              text: formObj.name,
              font: "normal small-caps normal 30px 楷体",
              style: Cesium.LabelStyle.FILL_AND_OUTLINE,

              fillColor: Cesium.Color.AZURE,
              outlineColor: Cesium.Color.BLACK,
              outlineWidth: 2,
              horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
              verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
              scaleByDistance: new Cesium.NearFarScalar(1000, 1.0, 20000, 0.5),
              distanceDisplayCondition: new Cesium.DistanceDisplayCondition(
                  0.0,
                  20000
              ),
              pixelOffset: new Cesium.Cartesian2(0, -16),
            },
            popup: {
              html:
                  '<div class="divpoint divpoint-theme-29baf1" style="pointer-events:all;">' +
                  '<div class="divpoint-wrap">' +
                  '<div class="area">' +
                  '<img class="imagegb" src="public/img/marker/关闭.png" alt="">' +
                  '<div class="title">' +
                  formObj.name +
                  '</div><div class="label-content"><div class="data-li" style="padding:4px"><div class="data-label"  style="max-width: 200px;word-wrap: break-word;word-break: break-all;overflow: hidden;display: inline-block;white-space: normal;">' +
                  "行政区划：" + formObj.town + "</br>类型：" + formObj.use + "</br>规划用途：" + formObj.type + "</br>位置：" + formObj.location + "</br>面积：" + formObj.area + "亩</br>" +
                  '<button onclick="clickme()">时序浏览</button></br>' +
                  '<button onclick="toggleClick(' + formObj.id + ')">立体净地</button></br></div></div></div></div></div><div class="b-t-l"></div><div class="b-b-r"></div></div></div>',
            },
          });

          window.viewer.dataSources.getByName("myland")[0].entities.add(_entity);
          window.viewer.dataSources
              .getByName("mylandpoint")[0]
              .entities.add(_pointEntity);
          window.viewer
              .flyTo(_entity, {offset: new Cesium.HeadingPitchRange(0, -1, 1000)})
              .then(() => {
                yjs.util.highlightEntity(_entity, {
                  time: 5, //闪烁时长（秒）
                  maxAlpha: 1,
                  color: Cesium.Color.YELLOW,
                  onEnd: function () {
                    //结束后回调
                  },
                });
              });

          // addRegionGraphics();
        }
    );

    //上传文件成功后
    const handleAvatarSuccess: UploadProps["onSuccess"] = (response, uploadFile) => {
      formObj.fileName = uploadFile.name
      formObj.geom = response;
      ElNotification({
        title: "传送地块数据",
        message: "上传成功",
        type: "success",
        position: "top-left",
        offset: 300,
      });
    };
    return {
      uploadFile,
      cityOption,
      typeOption,
      useOption,
      formObj,
      handleAvatarSuccess,
      clear,
      landTypeOption,
      dialogTimeVisible,
      batchUpload,
      upload,
      createLand,
      isUpload,
      value1,
      createUse
    };
  },
});
</script>

<style scoped lang="scss">
.common-table {
  .table-item {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 20px;

    .table-full-text {
      display: flex;
      width: 100%;
      align-items: center;

      .left {
        color: rgba(240, 245, 255, 0.95);
        padding-right: 10px;
        width: 61px;
      }

      .right {
        flex: 1;

        .red-line {
          display: flex;
          //align-items: center;
          .red-line-text {
            padding-right: 12px;
            color: #e9e9e9;
          }
        }
      }
    }
  }

  .empty-form-item {
    width: 280px;
  }

  .tips-text {
    margin-left: 62px;
    margin-top: -16px;
    color: #e9e9e9;
  }

  .tips-text1 {
    margin-left: 62px;
    color: #e9e9e9;
  }

  .fix-operate-map {
    width: 0;
  }
}

//.upload-demo {
//  .el-upload {
//    //&.el-upload--text {
//      &.is-drag {
//       background-color: #22ee22;
//        .el-upload-dragger {
//          background-color: #011f2f;
//          border: 1px dashed #409eff;
//        }
//      //}
//    }
//  }
//}

</style>
